<template>
  <div class="conetr h-full flex flex-col">
    <div class="center-board">
      <div class="center-title">
        <h3>组织施工</h3>
      </div>
      <div class="action-bar mb-[20px]">
        <el-button icon="Back" type="primary" plain text @click="backTo">返回</el-button>
        <el-button
          icon="Download"
          type="success"
          plain
          @click="handleSubmit"
          :disabled="!canEdit"
          :loading="loading"
        >
          保存
        </el-button>
      </div>
    </div>
    <div class="flex-1 overflow-auto">
      <el-form
        ref="baseFormRef"
        :model="formData"
        :rules="formRules"
        label-width="150px"
        class="form mb-0"
        :disabled="!canEdit"
      >
        <el-form-item label="开工日期" prop="constructionStartTime">
          <el-date-picker
            v-model="formData.constructionStartTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择开工日期"
          />
        </el-form-item>
        <el-form-item label="预计竣工日期" prop="constructionEndTime">
          <el-date-picker
            v-model="formData.constructionEndTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择预计竣工日期"
          />
        </el-form-item>
        <el-form-item label="开工仪式照片">
          <MultiImageUpload
            v-model="formData.constructionStartFile"
            :disabled="!canEdit"
            v-model:loading="constructionStartFileLoading"
          />
        </el-form-item>
        <el-form-item label="施工组织方案">
          <MultiImageUpload
            v-model="formData.constructionSchemeFile"
            :disabled="!canEdit"
            v-model:loading="constructionSchemeFileLoading"
          />
        </el-form-item>
        <el-form-item label="施工组织进度表">
          <MultiImageUpload
            v-model="formData.constructionPlanFile"
            :disabled="!canEdit"
            v-model:loading="constructionPlanFileLoading"
          />
        </el-form-item>
        <el-form-item label="装修许可证">
          <MultiImageUpload
            v-model="formData.constructionPermitFile"
            :disabled="!canEdit"
            v-model:loading="constructionPermitFileLoading"
          />
        </el-form-item>
      </el-form>
      <el-button v-if="canEdit" class="mb-[10px]" @click="handleAddWorKer">新增工人信息</el-button>
      <el-form
        ref="workInfoFormRef"
        :model="formData"
        :rules="formRules"
        class="form mb-[10px]"
        :disabled="!canEdit"
      >
        <BasePageTable :table-data="formData.workInfo" :table-columns-data="tableColumnsWorkData">
          <template #name="{ row, index }">
            <el-form-item :prop="'workInfo.' + index + '.name'" :rules="formRules.name">
              <el-input v-model="row.name" placeholder="请输入工人姓名" maxlength="20"></el-input>
            </el-form-item>
          </template>
          <template #mobile="{ row, index }">
            <el-form-item :prop="'workInfo.' + index + '.mobile'" :rules="formRules.mobile">
              <el-input
                v-model="row.mobile"
                placeholder="请输入工人联系方式"
                maxlength="15"
              ></el-input>
            </el-form-item>
          </template>
          <template #job="{ row, index }">
            <el-form-item :prop="'workInfo.' + index + '.job'" :rules="formRules.job">
              <el-select v-model="row.job" placeholder="请选择岗位" @change="row.brandId = ''">
                <el-option
                  v-for="item in WorkmanProfessionOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </template>

          <template #operation="{ row, index }">
            <el-button
              link
              type="danger"
              icon="Delete"
              @click="handleDelete(formData.workInfo, index)"
            >
              删除
            </el-button>
          </template>
        </BasePageTable>
      </el-form>
      <el-button v-if="canEdit" class="mb-[10px]" @click="handleAdd">新增隐蔽工程</el-button>

      <el-form
        ref="hiddenWorksFormRef"
        :model="formData"
        :rules="formRules"
        class="form mb-[10px]"
        :disabled="!canEdit"
      >
        <BasePageTable :table-data="formData.hiddenWorks" :table-columns-data="tableColumnsData">
          <template #type="{ row, index }">
            <el-form-item :prop="'hiddenWorks.' + index + '.type'" :rules="formRules.type">
              <el-select v-model="row.type" placeholder="请选择工程类型" clearable filterable>
                <el-option
                  v-for="item in hiddenWorksList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </template>
          <template #files="{ row, index }">
            <el-form-item :prop="'hiddenWorks.' + index + '.files'" :rules="formRules.files">
              <MultiImageUpload v-model="row.files" :disabled="!canEdit" />
            </el-form-item>
          </template>
          <template #remark="{ row, index }">
            <el-form-item :prop="'hiddenWorks.' + index + '.remark'" :rules="formRules.remark">
              <el-input v-model.trim="row.remark" placeholder="请输入备注"></el-input>
            </el-form-item>
          </template>
          <template #operation="{ row, index }">
            <el-button
              link
              type="danger"
              icon="Delete"
              @click="handleDelete(formData.hiddenWorks, index)"
            >
              删除
            </el-button>
          </template>
        </BasePageTable>
      </el-form>
      <div v-if="formData.remark">
        <el-form-item label="驳回理由">
          {{ formData.remark }}
        </el-form-item>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ElMessage } from "element-plus";
import HouseAPI, { ConsumerHouseConstructionSchemeForm, HiddenWork, WorkInfo } from "@/api/house";
import BasePageTable from "@/components/BasePageTable/index.vue";
import MultiImageUpload from "@/components/Upload/MultiImageUpload.vue";
import { useDictStore } from "@/store";
import { validatePhone } from "@/utils/formvalidate";
const dictStore = useDictStore();
const WorkmanProfessionOptions = dictStore.getDictionary("WorkmanProfession");

// 定义 emit，用于通知外部关闭事件
const emit = defineEmits(["update:modelValue", "loadData", "backTo"]);
const dialog = reactive({
  title: "",
  visible: false,
});
/*基础信息*/
const baseFormRef = ref();
/*工人信息*/
const workInfoFormRef = ref();
/*新增隐蔽工程*/
const hiddenWorksFormRef = ref();
const currentRow = ref({});
const constructionStartFileLoading = ref(false);
const constructionSchemeFileLoading = ref(false);
const constructionPlanFileLoading = ref(false);
const constructionPermitFileLoading = ref(false);
const hiddenWorksList = dictStore.getDictionary("HiddenWorks");
const tableColumnsWorkData = ref([
  {
    prop: "name",
    label: "工人姓名",
    showOverflowTooltip: true,
    customSlot: "name",
  },
  {
    prop: "mobile",
    label: "联系电话",
    showOverflowTooltip: true,
    customSlot: "mobile",
  },
  {
    prop: "job",
    label: "岗位",
    showOverflowTooltip: true,
    customSlot: "job",
  },
  {
    prop: "operation",
    label: "操作",
    width: 100,
    align: "center",
    customSlot: "operation", // 自定义插槽名称
  },
]);
const tableColumnsData = ref([
  {
    prop: "type",
    label: "隐蔽工程",
    showOverflowTooltip: true,
    customSlot: "type",
    width: 200,
  },
  {
    prop: "files",
    label: "施工照片",
    showOverflowTooltip: true,
    customSlot: "files",
  },
  {
    prop: "remark",
    label: "施工备注",
    showOverflowTooltip: true,
    customSlot: "remark",
    width: 200,
  },
  {
    prop: "operation",
    label: "操作",
    width: 100,
    align: "center",
    customSlot: "operation", // 自定义插槽名称
  },
]);

const defaultFormData: ConsumerHouseConstructionSchemeForm = {
  constructionEndTime: "",
  constructionPermitFile: [],
  constructionPlanFile: [],
  constructionSchemeFile: [],
  constructionStartFile: [],
  constructionStartTime: "",
  createBy: 0,
  createTime: "",
  hiddenWorks: [],
  houseId: 0,
  id: undefined,
  merchantUserId: 0,
  remark: "",
  status: undefined,
  updateBy: 0,
  updateTime: "",
  workInfo: [],
};
const formData = ref({
  ...defaultFormData,
});
const formRules = reactive({
  // budgetAmount: [{ required: true, message: "请输入预算金额", trigger: "blur" }],
  name: [{ required: true, message: "请输入工人姓名", trigger: "blur" }],
  job: [{ required: true, message: "请选择岗位", trigger: "change" }],
  type: [{ required: true, message: "请选择工程类型", trigger: "change" }],
  files: [{ required: true, message: "请上传施工照片", trigger: "change" }],
  mobile: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { validator: validatePhone, trigger: "blur" },
  ],
  constructionStartTime: [
    { required: true, message: "请选择开工日期", trigger: "change" },
    {
      validator: (rule, value, callback) => {
        if (
          value &&
          formData.value.constructionEndTime &&
          value > formData.value.constructionEndTime
        ) {
          callback(new Error("开工日期不能大于竣工日期"));
        } else {
          callback();
        }
      },
      trigger: "change",
      message: "开工日期不能大于竣工日期",
    },
  ],
  constructionEndTime: [
    { required: true, message: "请选择预计竣工日期", trigger: "change" },
    {
      validator: (rule, value, callback) => {
        if (
          value &&
          formData.value.constructionStartTime &&
          value < formData.value.constructionStartTime
        ) {
          callback(new Error("竣工日期不能小于开工日期"));
        } else {
          callback();
        }
      },
      message: "竣工日期不能小于开工日期",
    },
  ],
});
const loading = computed(
  () =>
    constructionStartFileLoading.value ||
    constructionSchemeFileLoading.value ||
    constructionPlanFileLoading.value ||
    constructionPermitFileLoading.value
);

function backTo() {
  emit("backTo");
}

async function handleSubmit() {
  const validate = await baseFormRef.value.validate();
  const validateWorkInfo = await workInfoFormRef.value.validate();
  const validateHiddenWorks = await hiddenWorksFormRef.value.validate();
  if (!validate || !validateWorkInfo || !validateHiddenWorks) return;
  try {
    const hiddenWorks = formData.value.hiddenWorks.map((item) => {
      return {
        ...item,
        files: JSON.stringify(item.files),
      };
    });
    await HouseAPI.houseConstructionSchemeEdit({
      ...formData.value,
      constructionStartFile: JSON.stringify(formData.value.constructionStartFile),
      constructionSchemeFile: JSON.stringify(formData.value.constructionSchemeFile),
      constructionPlanFile: JSON.stringify(formData.value.constructionPlanFile),
      constructionPermitFile: JSON.stringify(formData.value.constructionPermitFile),
      hiddenWorks,
    });
    ElMessage.success("成功");
    emit("loadData");
    emit("backTo");
    handleCloseDialog();
  } catch (error) {
    console.log("error", error);
  }
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  Object.assign(formData.value, defaultFormData);
  emit("update:modelValue", false); // 关闭弹窗
}
const canEdit = ref(true);
function showModal(val, cannotEdit = false) {
  dialog.visible = true;
  currentRow.value = val;
  const {
    constructionStartFile,
    constructionSchemeFile,
    constructionPlanFile,
    constructionPermitFile,
    workInfo,
    hiddenWorks = [],
  } = val.house.houseConstructionSchemeVO || {};
  const hiddenWorksList = hiddenWorks.map((item) => {
    return {
      ...item,
      files: JSON.parse(item.files || []),
    };
  });
  canEdit.value = !cannotEdit;
  Object.assign(formData.value, defaultFormData, val.house.houseConstructionSchemeVO, {
    houseId: val.houseId,
    hiddenWorks: hiddenWorksList,
    workInfo: workInfo || [],
    constructionStartFile: JSON.parse(constructionStartFile || "[]"),
    constructionSchemeFile: JSON.parse(constructionSchemeFile || "[]"),
    constructionPlanFile: JSON.parse(constructionPlanFile || "[]"),
    constructionPermitFile: JSON.parse(constructionPermitFile || "[]"),
  });
}

function handleDelete(tableData, index) {
  tableData.splice(index, 1);
}

function handleAdd() {
  formData.value.hiddenWorks.push({
    type: "",
    files: [],
    remark: "",
  } as HiddenWork);
}

function handleAddWorKer() {
  formData.value.workInfo.push({
    mobile: "",
    name: "",
  } as WorkInfo);
}

defineExpose({
  showModal,
});
</script>
<style style="scss" scoped>
@import "@/views/house/style/conetr.scss";
.form-container {
  height: 600px;
  overflow: auto;
}
</style>
